<template>
    <view class="container">
        <view class="question-list">
            <view class="title-img" v-if="isImg == 0">
                <img style="width: 100%;height: 100%;" :src="posterImage || list.thumb_image" alt="">
            </view>
            <view class="title-video" v-else>
                <video id="myVideo" class="video" object-fit="cover" :initial-time="initialTime" :src="video"
                    @timeupdate="onTimeUpdate" @ended="onVideoEnd" @pause="onVideoPause" @loadedmetadata="onVideoLoaded"
                    :enable-progress-gesture="false" :enable-play-gesture="false" :show-play-btn="true"
                    :show-center-play-btn="true" :show-fullscreen-btn="false" :show-progress="true"
                    :show-progress-gesture="false"></video>
            </view>
            <view class="title">
                <view class="name">
                    <view class="name-l">
                        {{ name }}
                    </view>
                </view>
                <view class="study">
                    <text class="tn-icon-video"></text>
                    <text style="margin-left: 6rpx;">{{ list.total_num }}人看过</text>
                </view>
                <view class="price">
                    <text style="font-size: 26rpx;">￥</text>
                    <text>{{ list.salesprice }}</text>
                </view>
                <view class="online"></view>
                <view class="contont">
                    {{ description }}
                </view>
                <tn-tabs :list="tabslist" :isScroll="false" :current="current" name="name" @change="change"></tn-tabs>
                <view class="content" v-if="current == 0" v-html="list.introduce">
                </view>
                <view class="content" v-if="current == 1">
                    <TreeNode v-for="item in chapterList" :key="item.id" :node="item" :level="0"
                        @node-click="onTreeNodeClick" />
                </view>
            </view>
            <!-- 未对接支付暂时注释 -->
            <!-- <view class="bottom fixed-bottom" v-if="list.is_free === 0 && list.is_buy === 0"> -->
            <!-- <view class="bottom">
                <view class="left">
                    <text style="font-size: 26rpx;">￥</text>
                    <text>{{ list.salesprice }}</text>
                </view>
                <view class="right">
                    立刻学习
                </view>
            </view> -->
            <!-- <view class="bottom fixed-bottom" v-else>
                <view class="right" style="width: 100%;" @click="returnToParentChapter">
                    返回章节
                </view>
            </view> -->
        </view>
        <!-- <tui-no-data imgUrl="/static/img/img_noorder_3x.png" v-if="list.length == 0">暂无数据</tui-no-data> -->

    </view>
</template>

<script>
import newsApi from "@/common/api/news.js"
import TreeNode from "@/components/TreeNode.vue";
export default {
    components: {
        TreeNode
    },
    data() {
        return {
            showLoading: false,
            showNodata: true,
            list: [],//整体数据
            chapterList: [],//章节数据
            name: '',//章节名称
            loadFlag: 'loading',
            current_page: 1,
            has_more: false,
            category_id: '',
            description: '',
            tabslist: [{
                name: '详情介绍'
            }, {
                name: '课程列表'
            }],
            current: 0,
            isImg: 0,//判断是否展示章节视频及立刻学习按钮
            video: '', // 存储视频地址
            posterImage: '', // 存储海报图片地址
            originalChapterList: [], // 存储原始章节列表，用于返回上一级
            initialTime: 0,//播放位置
            currentTime: 0,      // 当前播放进度
            videoDuration: 0,    // 视频总时长
            videoContext: null,  // 视频上下文
            lastReportedTime: 0, // 上次上报的时间（用于节流）
            chapterId: null,//本章节id
            justSwitchedChapter: false, // 新增：切换章节时阻止首次保存进度
            isVideoLoaded: false, // 视频是否已加载完成
            saveProgressTimer: null, // 保存进度的定时器
            pendingProgressSave: false, // 是否有待保存的进度
            isSwitchingChapter: false, // 是否正在切换章节
            hasActuallyWatched: false, // 是否真正观看了当前视频
            lastWatchedTime: 0, // 上次真正观看的时间
        }
    },
    computed: {
    },
    onLoad(params) {
        this.videoContext = uni.createVideoContext('myVideo', this);
        console.log('params', params);
        this.category_id = params.category_id
        this.description = params.description
        this.search()
    },
    onShow() {
        const token = uni.getStorageSync('token')
        const user = uni.getStorageSync('user')
        if (!token && !user) {
            uni.showToast({
                title: "请先登录",
                icon: "none",
            });
            setTimeout(() => {
                this.utils.goto('/pages/index/index')
            }, 1500);
        }
    },
    onUnload() {
        // 页面卸载时保存当前进度
        this.saveCurrentProgress();
        // 清除定时器
        if (this.saveProgressTimer) {
            clearTimeout(this.saveProgressTimer);
        }
    },
    async onReachBottom() {
    },
    methods: {
        // 视频加载完成
        onVideoLoaded(e) {
            this.isVideoLoaded = true;
            this.videoDuration = e.detail.duration;
            console.log('视频加载完成，总时长:', this.videoDuration);

            // 延迟执行，确保DOM元素已渲染
            setTimeout(() => {
                this.disableProgressBarInteraction();
            }, 500);
        },

        // 禁用进度条交互
        disableProgressBarInteraction() {
            try {
                // 查找所有可能的进度条元素并禁用交互
                const progressElements = document.querySelectorAll('[class*="progress"], [class*="slider"], .uni-video-progress, .uni-video-progress-bar, .uni-video-progress-handle');
                progressElements.forEach(element => {
                    element.style.pointerEvents = 'none';
                    element.style.userSelect = 'none';
                    element.style.webkitUserSelect = 'none';
                });

                // 禁用视频元素的进度条交互
                const videoElement = document.querySelector('#myVideo');
                if (videoElement) {
                    videoElement.style.pointerEvents = 'auto';
                    // 添加事件监听器阻止进度条相关事件
                    videoElement.addEventListener('click', (e) => {
                        // 如果点击的是进度条区域，阻止默认行为
                        if (e.target.classList.contains('progress') ||
                            e.target.classList.contains('slider') ||
                            e.target.closest('[class*="progress"]') ||
                            e.target.closest('[class*="slider"]')) {
                            e.preventDefault();
                            e.stopPropagation();
                        }
                    });
                }

                console.log('进度条交互已禁用');
            } catch (error) {
                console.log('禁用进度条交互时出错:', error);
            }
        },

        // 监听播放进度更新
        onTimeUpdate(e) {
            if (this.justSwitchedChapter) {
                this.justSwitchedChapter = false;
                return; // 阻止切换章节后首次触发的保存
            }

            if (this.isSwitchingChapter) {
                return; // 切换章节时不上报进度
            }

            this.currentTime = e.detail.currentTime;
            this.videoDuration = e.detail.duration;

            // 检查是否真正观看了视频（播放时间超过5秒）
            if (this.currentTime > 5) {
                this.hasActuallyWatched = true;
            }

            // 只有在真正观看过的情况下才保存进度
            if (this.hasActuallyWatched) {
                // 节流处理：每15秒自动保存一次进度，避免频繁请求
                if (this.currentTime - this.lastReportedTime > 15) {
                    this.scheduleProgressSave();
                    this.lastReportedTime = this.currentTime;
                }
            }
        },

        // 视频结束
        onVideoEnd() {
            console.log('视频播放结束');
            this.currentTime = this.videoDuration; // 确保进度为100%
            this.saveVideoProgress(100); // 强制保存100%进度
        },

        // 视频暂停
        onVideoPause() {
            console.log('视频暂停，当前时间:', this.currentTime);
            this.saveVideoProgress();
        },

        // 调度进度保存（防抖）
        scheduleProgressSave() {
            if (this.saveProgressTimer) {
                clearTimeout(this.saveProgressTimer);
            }

            this.pendingProgressSave = true;
            this.saveProgressTimer = setTimeout(() => {
                if (this.pendingProgressSave) {
                    this.saveVideoProgress();
                    this.pendingProgressSave = false;
                }
            }, 2000); // 2秒后保存，避免频繁请求
        },

        // 保存当前进度（页面卸载时调用）
        saveCurrentProgress() {
            if (this.chapterId && this.currentTime > 0 && this.videoDuration > 0) {
                this.saveVideoProgress();
            }
        },

        async refreshChapterList() {
            let params = { course_id: this.category_id };
            try {
                const res = await newsApi.xilueduDetail(this, params);
                if (res.code == 1) {
                    // 只更新章节进度数据，不重置结构
                    // 递归更新章节的 view_time 和 view_progress
                    const updateProgress = (oldList, newList) => {
                        if (!Array.isArray(oldList) || !Array.isArray(newList)) return;
                        oldList.forEach(oldItem => {
                            const newItem = newList.find(n => n.id === oldItem.id);
                            if (newItem) {
                                oldItem.view_time = newItem.view_time;
                                oldItem.view_progress = newItem.view_progress;
                                if (oldItem.children && newItem.children) {
                                    updateProgress(oldItem.children, newItem.children);
                                }
                            }
                        });
                    };
                    updateProgress(this.list.course_file, res.data.course_file);
                    updateProgress(this.chapterList, res.data.course_file); // 保证当前显示的章节也同步
                }
            } catch (e) {
                console.error('刷新章节进度失败', e);
            }
        },

        async saveVideoProgress(forceProgress = null) {
            // 避免无效进度保存
            if (!this.chapterId || this.videoDuration < 1) {
                console.log('跳过保存：章节ID或视频时长无效');
                return;
            }

            // 如果不是强制保存且没有真正观看过，则跳过
            if (forceProgress === null && !this.hasActuallyWatched) {
                console.log('跳过保存：未真正观看视频');
                return;
            }

            try {
                let progress;
                let viewTime;

                if (forceProgress !== null) {
                    // 强制设置进度（如视频结束时设为100%）
                    progress = forceProgress;
                    viewTime = this.videoDuration;
                } else {
                    // 正常计算进度
                    if (this.currentTime < 1) {
                        console.log('跳过保存：当前播放时间过短');
                        return;
                    }
                    progress = Math.min(100, Math.round((this.currentTime / this.videoDuration) * 100));
                    viewTime = this.currentTime;
                }

                console.log('保存进度:', {
                    chapterId: this.chapterId,
                    currentTime: this.currentTime,
                    videoDuration: this.videoDuration,
                    progress: progress,
                    viewTime: viewTime,
                    hasActuallyWatched: this.hasActuallyWatched
                });

                let params = {
                    course_id: this.category_id,
                    course_file_id: this.chapterId,
                    view_time: viewTime,
                    view_progress: progress.toString(),
                    type: 1
                }

                const res = await newsApi.playTime(this, params);
                if (res.code == 1) {
                    console.log('进度保存成功');
                    // 延迟刷新章节列表，避免频繁请求
                    setTimeout(() => {
                        this.refreshChapterList();
                    }, 1000);
                } else {
                    console.error('进度保存失败:', res.msg);
                }
            } catch (error) {
                console.error('保存进度失败:', error);
            }
        },

        // 详情数据
        search() {
            let params = {
                course_id: this.category_id
            }
            newsApi.xilueduDetail(this, params).then(res => {
                console.log('res-wy', res);
                if (res.code == 1) {
                    this.list = res.data
                    this.chapterList = this.list.course_file
                    this.originalChapterList = this.list.course_file
                    this.name = this.list.name
                }
            })
        },

        // tabs切换
        change(index) {
            // 判断是否切换到课程列表tab，且需要会员,is_charge代表当前课程是否付费(1付费)，is_vip（0不是会员）是否购买会员
            if (index === 1 && this.list.is_charge == 1 && this.list.is_vip == 0) {
                uni.showToast({
                    title: '请开通会员后查看',
                    icon: 'none'
                });
                // 这里可选：如果需要跳转页面，可在此添加uni.navigateTo({ url: '你的会员开通页路径' })
                return;
            }
            this.current = index;
        },

        // 章节详情
        async chapter(id) {
            // 如果当前正在播放视频且真正观看过，才保存进度
            if (this.isImg === 1 && this.chapterId && this.hasActuallyWatched) {
                await this.pauseAndSaveProgress();
            }
            // 切换到新章节
            this.switchToChapter(id);
        },

        // 新增：树节点点击事件
        onTreeNodeClick(node) {
            this.chapter(node.id);
        },

        // 暂停视频并保存进度
        async pauseAndSaveProgress() {
            try {
                if (this.videoContext) {
                    this.videoContext.pause();
                }
                // 等待一小段时间确保暂停完成
                await new Promise(resolve => setTimeout(resolve, 100));
                // 只有在真正观看过的情况下才保存进度
                if (this.hasActuallyWatched) {
                    await this.saveVideoProgress();
                }
            } catch (e) {
                console.error('暂停并保存进度失败', e);
            }
        },

        // 切换到新章节的逻辑
        switchToChapter(id) {
            // 查找匹配ID的章节
            const chapter = this.findChapterById(this.chapterList, id);
            if (chapter) {
                // 重置视频相关状态
                this.isVideoLoaded = false;
                this.pendingProgressSave = false;
                this.isSwitchingChapter = true; // 设置正在切换章节状态
                this.hasActuallyWatched = false; // 重置观看状态
                this.lastWatchedTime = 0; // 重置观看时间

                // 设置视频和名称信息
                this.video = chapter.file || '';
                this.initialTime = chapter.view_time || 0;
                this.currentTime = chapter.view_time || 0; // 使用保存的播放位置
                this.name = chapter.name || this.name;
                this.posterImage = chapter.poster_image || '';
                this.chapterId = chapter.id;
                this.justSwitchedChapter = true; // 切换章节时阻止首次保存进度

                // 检查是否有子章节
                if (chapter.children && chapter.children.length > 0) {
                    // Has children, show image and update chapter list
                    this.isImg = 0;
                    // 保存当前章节列表，用于返回上一级
                    this.originalChapterList = this.chapterList;
                    // 更新为子章节列表
                    this.chapterList = chapter.children;
                } else {
                    // No children, show video
                    this.isImg = 1;
                    console.log('切换到视频章节:', chapter);
                }
                // 切换完成后，短暂延迟后重置 isSwitchingChapter 状态，允许进度保存
                setTimeout(() => {
                    this.isSwitchingChapter = false;
                }, 500);
            } else {
                console.log('未找到匹配的章节');
            }
        },

        // 根据ID查找章节的辅助函数
        findChapterById(chapterList, id) {
            for (const chapter of chapterList) {
                if (chapter.id === id) {
                    return chapter;
                }

                // 递归查找子章节
                if (chapter.children && chapter.children.length > 0) {
                    const result = this.findChapterById(chapter.children, id);
                    if (result) {
                        return result;
                    }
                }
            }
            return null;
        },

        // 返回上一级章节列表
        // returnToParentChapter() {
        //     console.log('length',this.originalChapterList.length);
        //     if (this.originalChapterList && this.originalChapterList.length > 0) {
        //         this.chapterList = this.originalChapterList;
        //         // 重置原始列表，以便再次下钻
        //         this.originalChapterList = this.list.course_file;
        //     }
        // }
    }
}
</script>

<style scoped lang="scss">
.container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    /* 确保容器占满视口高度 */
}

.question-list {
    flex: 1;
    /* 内容区域自动填充剩余空间 */
    background: #ffffff;

    .title-img {
        height: 400rpx;
        width: 100%;
    }

    .title-video {
        width: 100%;
        height: 360rpx;

        .video {
            width: 100%;
            height: 100%;
        }

        /* 禁用进度条交互 */
        /deep/ .uni-video-progress {
            pointer-events: none !important;
        }

        /deep/ .uni-video-progress-bar {
            pointer-events: none !important;
        }

        /deep/ .uni-video-progress-handle {
            pointer-events: none !important;
        }

        /* 通用进度条禁用 */
        /deep/ [class*="progress"] {
            pointer-events: none !important;
        }

        /deep/ [class*="slider"] {
            pointer-events: none !important;
        }

        /* 确保视频控件中的进度条不可交互 */
        /deep/ video::-webkit-media-controls-timeline {
            pointer-events: none !important;
        }

        /deep/ video::-webkit-media-controls-play-button {
            pointer-events: auto !important;
        }
    }

    .title {
        margin-top: 20rpx;
        padding: 0 20rpx;

        .name {
            display: flex;
            align-items: center;

            .name-l {
                font-size: 36rpx;
                font-weight: bold;
            }

            .name-r {
                margin-left: 20rpx;
                color: #ffffff;
                padding: 8rpx 26rpx;
                background: #5677fc;
                border-radius: 26rpx;
                font-size: 24rpx;
            }
        }

        .study {
            margin-top: 20rpx;
        }

        .price {
            margin-top: 20rpx;
            font-size: 38rpx;
            color: red;
        }

        .online {
            width: 100%;
            height: 1rpx;
            background: #666666;
            margin: 10rpx 0;
        }

        .contont {
            color: #666666;
            margin-bottom: 20rpx;
        }

        .content {
            margin-bottom: 100rpx;
            font-size: 30rpx;

            .content-list {
                display: flex;
                margin-top: 20rpx;

                .list-img {
                    width: 350rpx;
                    height: 200rpx;

                    image {
                        width: 100%;
                        height: 100%;
                        border-radius: 10rpx;
                    }
                }

                .title {
                    font-weight: bold;
                }
            }
        }
    }


}

.bottom {
    border-top: 1px solid #eeeeee;
    padding: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left {
        color: red;
        font-size: 38rpx;
    }

    .right {
        padding: 10rpx 30rpx;
        color: #ffffff;
        background: #5677fc;
        border-radius: 30rpx;
    }
}

.fixed-bottom {
    padding: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #ffffff;
    /* 可选：添加阴影效果 */
    position: relative;
    /* 确保在容器内定位 */
    z-index: 10;
    /* 防止被内容覆盖 */
}
</style>
